package org.example.graphx.local

import org.apache.spark.graphx.{GraphLoader, PartitionStrategy}
import org.apache.spark.sql.SparkSession

object TriangleCountingExample {

  def main(args: Array[String]): Unit = {

    // 创建一个SparkSession
    val spark = SparkSession
      .builder
      .master("local")
      .appName("graphx-triangleCounting")
      .getOrCreate()
    val sc = spark.sparkContext

    // 按规范顺序加载边
    val graph = GraphLoader.edgeListFile(sc, "data/graphx/followers.txt", true)
      .partitionBy(PartitionStrategy.RandomVertexCut)

    // 计算每个顶点所在的三角数量
    val triCounts = graph.triangleCount().vertices

    // 将节点映射为人物名称
    val users = sc.textFile("data/graphx/users.txt").map { line =>
      val fields = line.split(",")
      (fields(0).toLong, fields(1))
    }
    val triCountByUsername = users.join(triCounts).map { case (id, (username, tc)) =>
      (username, tc)
    }

    // 在控制台输出结果
    println(triCountByUsername.collect().mkString("\n"))

    spark.stop()
  }

}
